package dbmanager

import (
	"reflect"
	"github.com/astaxie/beego/orm"
	"fmt"
	"cloud_worm/util/umodels/mysqldb"
)

type RouterConfig struct {
	Id 				int64
	Version			string
	ConfigUrl 		string
	ServerAddress	string
	IntervalTime 	int
	HeartbeatTimeout 	int

	Created 			int64
	Updated 			int64
	Status 				int
}

func (r *RouterConfig) TableName() string {
	return reflect.TypeOf(*r).Name()
}

func (r *RouterConfig) Read(fields ...string) error {
	err := orm.NewOrm().Read(r, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", r.TableName(), err.Error())
	}
	return nil
}

func (r *RouterConfig) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(r, fields...)
	if err != nil {
		return fmt.Errorf("%s, %s", r.TableName(), err.Error())
	}
	return nil
}

func (r *RouterConfig) Insert() error {
	_, err := orm.NewOrm().Insert(r)
	if err != nil {
		return fmt.Errorf("%s, %s", r.TableName(), err.Error())
	}

	return nil
}

func init()  {
	orm.RegisterModel(new(RouterConfig))
}

func (r *RouterConfig) SelectCount(status int) (int64, error) {
	qs := orm.NewOrm().QueryTable(r)
	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}

	count, err := qs.Count()
	if err != nil {
		return 0, err
	}

	return count, nil
}

func (r *RouterConfig) SelectWithStatus(offset int, limit int, status int) ([]*RouterConfig, error) {
	var routes []*RouterConfig

	qs := orm.NewOrm().QueryTable(r).Offset(offset).Limit(limit)

	if status != mysqldb.StatusAll {
		qs = qs.Filter("status", status)
	}
	qs.OrderBy("-version")

	_, err := qs.All(&routes)
	if err != nil {
		return nil, err
	}

	return routes, nil
}